<!--
 * @Author: 冯尚新 fengshangxin@yunjinhz.com
 * @Date: 2023-05-23 10:51:56
 * @LastEditors: 冯尚新 fengshangxin@yunjinhz.com
 * @LastEditTime: 2023-06-01 16:21:13
 * @FilePath: \zmglpt-ui-mobile-v1.1\dev\pages\case\official\checkRecordDoc.vue
 * @Description: 案件-检查（勘验）笔录文书
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="false" backText="返回" :title="navTitle">
      <view class="white-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view style="width: calc(100% + 30px);">
        <form-section title="现场笔录"></form-section>
      </view>
      <u-form :model="docRecordform" :error-type="errorType" :rules="rules" class="form-content" ref="uForm">
        <u-form-item
          label="检查开始时间"
          :required="isRequired"
          prop="checkTimeS"
          right-icon="arrow-right"
          :label-position="labelPosition"
          ref="changeRefS"
        >
          <u-input
            placeholder="请选择开始时间"
            :disabled="true"
            :clearable="false"
						:custom-style="pointerStyle"
            v-model="docRecordform.checkTimeS"
            @click="()=>{if(state.canEdit) clicDatekHandle('isShowCheckS')}"
          />
        </u-form-item>
        <u-form-item
          label="检查结束时间"
          :required="isRequired"
          prop="checkTimeE"
          right-icon="arrow-right"
          :label-position="labelPosition"
          ref="changeRefE"
        >
          <u-input
            placeholder="请选择结束时间"
            :disabled="true"
            :clearable="false"
						:custom-style="pointerStyle"
            v-model="docRecordform.checkTimeE"
            @click="()=>{if(state.canEdit) clicDatekHandle('isShowCheckE')}"
          />
        </u-form-item>
        <u-form-item :border-bottom="false" label-width="auto" label="检查地点" prop="checkAddress" label-position="left">
          <u-icon
            slot="right"
            customPrefix="csbi-icon"
            name="moban"
            size="40"
            v-if="!isSimpleCase()"
            :color="$theme.u_type_primary"
            @click="tapFieldPress('checkAddress')"
          ></u-icon>
        </u-form-item>
        <u-form-item label="" label-position="top">
          <u-input
            placeholder="请输入检查地点"
            :disabled="!state.canEdit"
            v-model="docRecordform.checkAddress"
            maxlength="100"
          />
        </u-form-item>
        <u-form-item label="被检查人" prop="partyNames" :label-position="labelPosition" :required="isRequired" right-icon="arrow-right">
          <u-input
            placeholder="请选择被检查人"
            :disabled="true"
            v-model="partyNames"
						:custom-style="pointerStyle"
            @click="()=>{if(state.canEdit) partySelectShow = true}"
          />
        </u-form-item>
        <u-form-item
          label="现场负责人"
          prop="locPic"
          :label-width="labelWidth"
          :required="isRequired && curPartyPerson.partyType == '02'"
        >
          <u-input
            input-align="right"
            placeholder="请输入现场负责人"
            :disabled="!state.canEdit"
            v-model="docRecordform.locPic"
            maxlength="50"
          />
        </u-form-item>
        <u-form-item label="性别" :label-width="labelWidth">
          <dic-input
            input-align="right"
            :keyWord="$u.dic.DIC_KEYS.BSC_GENDDER"
            :dicCode="docRecordform.locPicSex"
            :border="border"
            type="select"
            :select-open="dicSelectOpen('sex',$u.dic.DIC_KEYS.BSC_GENDDER)"
            placeholder="请选择"
            :disabled="!state.canEdit"
            v-model="docRecordform.locPicSexName"
            @changeInputModelData="(name)=>{$set(docRecordform, 'locPicSexName', name)}"
            @click="showDic($u.dic.DIC_KEYS.BSC_GENDDER,docRecordform.locPicSex,'sex')"
          />
        </u-form-item>
        <u-form-item label="证件类型" :label-width="labelWidth">
          <dic-input
            input-align="right"
            :keyWord="$u.dic.DIC_KEYS.IDCARD_TYPE"
            :dicCode="docRecordform.locPicIdType"
            :border="border"
            type="select"
            :select-open="dicSelectOpen('card',$u.dic.DIC_KEYS.IDCARD_TYPE)"
            placeholder="请选择"
            :disabled="!state.canEdit"
            v-model="docRecordform.locPicIdTypeName"
            @changeInputModelData="(name)=>{$set(docRecordform, 'locPicIdTypeName', name)}"
            @click="showDic($u.dic.DIC_KEYS.IDCARD_TYPE,docRecordform.locPicIdType,'card')"
          />
        </u-form-item>
        <u-form-item label="证件号码" :label-position="labelPosition" prop="locPicIdNo">
          <u-input placeholder="请输入证件号码" :disabled="!state.canEdit" maxlength="50" v-model="docRecordform.locPicIdNo" />
        </u-form-item>
        <u-form-item label="联系电话">
          <u-input placeholder="请输入联系电话" :disabled="!state.canEdit" type="number" v-model="docRecordform.checkPhone" />
        </u-form-item>
        <u-form-item
          label="与被检查人关系"
          prop="relation"
          :label-width="labelWidth"
          :label-position="labelPosition"
        >
          <u-input
            placeholder="请输入与被检查人关系"
            :disabled="!state.canEdit"
            v-model="docRecordform.relation"
            maxlength="50"
          />
        </u-form-item>
        <u-form-item
          label="告项"
          prop="alkItem"
          :bordebottom="false"
          label-width="auto"
          label-position="left"
        >
          <u-icon
            slot="right"
            customPrefix="csbi-icon"
            name="moban"
            size="40"
            :color="$theme.u_type_primary"
            @click="tapFieldPress('talkItem')"
          ></u-icon>
        </u-form-item>
        <u-form-item label="" label-position="top">
          <u-input
            type="textarea"
            :maxlength="maxLength"
            placeholder="请输入告知事项"
            :disabled="!state.canEdit"
            v-model="docRecordform.talkItem"
          />
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-title">
                现场情况
              </view>
              <view class="uicon-sty" @click="tapFieldPress('localeDesc')">
                <u-icon :color="$theme.u_type_primary" customPrefix="csbi-icon" name="moban" size="40"></u-icon>
              </view>
            </view>
            <view class="p-content">
              <u-input
                type="textarea"
                placeholder="请填写现场情况"
                :maxlength="maxLength"
                :disabled="!state.canEdit"
                v-model="docRecordform.localeDesc"
              />
            </view>
          </view>
        </u-form-item>

        <u-form-item
          label="被检查人或者现场负责人意见"
          prop="byCheckAdvice"
          label-width="auto"
          label-position="left"
          :border-bottom="false"
        >
          <u-icon
            slot="right"
            customPrefix="csbi-icon"
            name="moban"
            :color="$theme.u_type_primary"
            size="40"
            @click="tapFieldPress('byCheckAdvice')"
          ></u-icon>
        </u-form-item>
        <u-form-item
          label=""
          label-position="top"
        >
          <u-input
            type="textarea"
            maxlength="500"
            placeholder="请输入当事人或被检查人意见"
            :disabled="!state.canEdit"
            v-model="docRecordform.byCheckAdvice"
          />
        </u-form-item>

        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-title">
                检查人
              </view>
              <view class="uicon-sty" @click="()=>{if(state.canEdit) addPerson()}">
                <u-icon name="plus-circle" :color="$theme.u_type_primary" size="40"></u-icon>
              </view>
            </view>
            <view class="p-content" v-for="(item,index) in employeeLst" :key="index">
              <text class="p-width">
                {{ item.personName }}
              </text>
              <text>
                {{ item.leCertNo || item.inspectionCertNo }}
              </text>
            </view>
          </view>
        </u-form-item>
      </u-form>
    </view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls" v-if="state.canEdit">
      <u-button plain class="u-btn" type="primary" @click="submitBtn('save')">
        保存
      </u-button>
      <u-button class="u-btn" type="primary" @click="submitBtn('submit')">
        提交
      </u-button>
    </view>
    <!-- 底部按钮结束 -->

    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <!-- 时间处理 -->
    <u-picker mode="time" :params="paramsDate" v-model="isShowCheckS" @confirm="changeDate('checkTimeS',$event)">
    </u-picker>
    <u-picker mode="time" :params="paramsDate" v-model="isShowCheckE" @confirm="changeDate('checkTimeE',$event)">
    </u-picker>
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="dicShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
    <u-popup mode="bottom" height="80%" v-model="showFieldTpl">
      <doc-form-content-tep
        :params="fieldParam"
        formName="docRecordform"
        :fieldkey="fieldKey"
        @choice="choiceFieldTpl"
      ></doc-form-content-tep>
    </u-popup>
    <u-popup mode="bottom" height="80%" v-model="partySelectShow">
      <select-party-component :params="partyParams" @choose="handlerChooseParty"></select-party-component>
    </u-popup>
  </view>
</template>

<script>
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import caseCommon from "../caseCommonMixin.js";
	import {
		IDCARD_TYPE_CODE,
		CASE_TYPE,
	} from '@/service/case/mapping/index.js';
	import officeService from "@/service/case/office.service.js";
	import DicChoice from "@/components/dic_choice.vue";
	import DicInput from "@/components/dic_input.vue";
	import DocFormContentTep from "../components/docFormContentTemplate.vue";
	import zjCommonService from "@/service/common/common.service";
	import caseService from '@/service/case/case.service.js';
	import SelectPartyComponent from "../components/selectPartyComponent.vue";
	import FormSection from "@/components/form-section.vue";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			"dic-choice": DicChoice,
			"dic-input": DicInput,
			PersonSelection,
			DocFormContentTep,
			SelectPartyComponent,
			FormSection,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				IDCARD_TYPE_CODE,
				paramsDate: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
					timestamp: true,
				},
				border: false,
				dicType: "",
				dicShow: false, // dic_select 是否显示
				dicKeyWords: "", // dic 关键字
				dicCurrentSelect: "", // dic 当前选择项
				isRequired: true,
				errorType: ['border-bottom', 'message', ],
				labelWidth: '380',
				labelPosition: 'top',
				maxLength: 32700,
				content: '',
				isShowModal: false, // 点击提交按钮弹窗提示
				isShowCheckS: false,
				isShowCheckE: false,
				isShowSaveBtn: false, // 是否显示保存按钮
				isShowPrintBtn: false, // 是否显示打印按钮
				isShowSumbitBtn: false, // 是否显示提交按钮
				isCanClick: false, // 是否可点击承办人按钮
				personSelectShow: false,
				psParam: {},
				caseParam: {}, // 文书列表中传过来的参数
				rules: {
					checkTimeS: [{
						required: true,
						message: '请选择开始时间',
						trigger: ['change', 'blur', ],
					}, ],
					checkTimeE: [{
						required: true,
						message: '请选择结束时间',
						trigger: ['change', 'blur', ],
					}, {
						validator: () => {
							return this.docRecordform['checkTimeE'] < this.docRecordform['checkTimeS'] ?
								false : true;
						},
						message: '结束时间必须大于开始时间',
					}, ],
					locPicIdNo: [{
						validator: (rule, value, callback) => {
							// 证件类型选择身份证，校验身份证号
							if ((this.docRecordform.locPicIdType == IDCARD_TYPE_CODE.IDENTIFICATION || this
									.docRecordform.locPicIdType == IDCARD_TYPE_CODE.TEMID) && !this.$u.test.isEmpty(value)) {
								return this.$u.test.idCard(value);
							} else {
								return true;
							}
						},
						message: '身份证号码不正确',
						trigger: ['change', 'blur', ],
					}, ],
					locPic: [{
						validator: (rule, value, callback) => {
							// 证件类型选择身份证，校验身份证号
							if (this.curPartyPerson.partyType == '02') {
								return !this.$u.test.isEmpty(value);
							} else {
								return true;
							}
						},
						message: '请输入被检查人',
						trigger: ['change', 'blur', ],
					}, ],
				},
				doc: {},
				docRecordform: {},
				employeeLst: [],
				saveData: {},
				signImgList: [],
				btnType: "",
				isReadBoolean: false,
				partySelectShow: false,
				partyNames: '', // 当事人名称
				partyList: [], // 当事人列表
				partyParams: {}, // 传给当事人选择页面的参数
				curPartyPerson: {}, // 当前选择的当事人
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}],
				// h5端部分浏览器input设置disabled后点击事件失效 2023-10-27 fsx start
				pointerStyle: {
				  marginRight: "5px",
					pointerEvents: "none !important"
				},
				// h5端部分浏览器input设置disabled后点击事件失效 2023-10-27 fsx end
			}
		},
		watch: {
			isShowCheckS() {
				this.$refs.changeRefS.validation();
			},
			isShowCheckE() {
				this.$refs.changeRefE.validation();
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
			console.log('参数：' + JSON.stringify(this.caseParam));
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo ? docInfo : {};
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			checkboxChange(e) {
				console.log(e);
				this.isReadBoolean = e;
				if (this.isReadBoolean) {
					this.docRecordform.isRead = 1;
				}
			},
			isSimpleCase() {
				return this.caseParam.caseType == CASE_TYPE.SIMPLE;
			},
			// 获取当事人list（多选）
			getPartyInfoList() {
				caseService.getPartyInfoList(this.caseParam.bizUuid).then(res => {
					if (!res.success) return;
					let names = [];
					this.partyList = res.data.length > 0 ? res.data : [];
					// 修改  partyUuids 为空时候 报错 fsx  start
					let pT = [];
					if (!!this.docRecordform.partyUuids) {
						this.partyList.forEach(itm => {
							if (this.docRecordform.partyUuids.indexOf(itm.partyUuid) != -1) {
								itm.check = true;
								names.push(itm.partyName);
							}
						});
						pT = this.partyList.filter(io => {
							return this.docRecordform.partyUuids.indexOf(io.partyUuid) != -1;
						});
					}
					// 修改  partyUuids 为空时候 报错 fsx  end
					if (pT.length > 0) {
						this.curPartyPerson = pT[0];
					}
					this.partyNames = names.join(',');
					this.partyParams = {
						list: this.partyList,
						selUsersStr: this.docRecordform.partyUuids,
					}
				}).catch((err) => {
					this.partyList = [];
					console.log(err);
				});
			},
			dicSelectOpen: function(type, keyWords) {
				if (type == this.dicType) {
					if (this.dicKeyWords == keyWords && this.dicShow) {
						return true;
					}
					return false;
				}
			},
			showDic: function(key, cur, type) {
				if (!this.state.canEdit) return;
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
				this.dicType = type;
			},
			selectDicConfirm: function(e) {
				// 类型
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.IDCARD_TYPE) {
					this.docRecordform.locPicIdTypeName = e[0].label;
					this.docRecordform.locPicIdType = e[0].extra.bcbCode;
					this.docRecordform.locPicIdType && this.docRecordform.locPicIdNo && (this.docRecordform.locPicIdNo = "");
				} else if (this.dicKeyWords == this.$u.dic.DIC_KEYS.BSC_GENDDER) {
					this.docRecordform.locPicSexName = e[0].label;
					this.docRecordform.locPicSex = e[0].extra.bcbCode;
				}
			},
			// 初始化文书信息
			initDocData() {
				this.$u.loading('加载中...');
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						this.docFields = [...docConfigs.data, ];
						// 获取勘验笔录信息参数
						let parms = {
							id: this.caseParam.id,
							docUuid: this.caseParam.docUuid,
							bizUuid: this.caseParam.bizUuid,
						}
						officeService.getDocCheckRecord(parms).then(res => {
							this.$u.hideLoading();
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
								rs.idCardType == '01' && (rs.idCardType = '2801');
							} else {
								rs = res.data[0];
							}
							let employeeList = this.parseEmployee(rs);
							this.employeeLst = employeeList;
							this.docRecordform = rs;
							this.getPartyInfoList();
						}).catch(er => {
							console.log(er);
							this.$u.hideLoading();
							this.$u.toast(er);
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				}).catch(er => {
					console.log(er);
					this.$u.hideLoading();
					this.$u.toast(er);
				});
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.submitBtn('preview');

				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			// 添加承办人事件
			addPerson() {
				this.psParam = {
					min: 2,
					max: 2,
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				this.employeeLst = [...e, ];
				let tIds = [];
				let tNames = [];
				this.employeeLst.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + "(" + el.leCertNo + ")");
				});
				this.docRecordform['undertakerUuids'] = tIds.join(",");
				this.docRecordform['undertaker'] = tNames.join(",");
			},
			// 选择当事人回调事件
			handlerChooseParty(e) {
				this.partySelectShow = false;
				if (e.list.length > 0) {
					this.curPartyPerson = e.list[0];
				} else {
					this.curPartyPerson = {};
				}
				this.partyNames = e.partyNames;
				this.partyParams.selUsersStr = e.partyUuids;
				this.docRecordform.partyUuids = e.partyUuids;
			},
			clicDatekHandle(type) {
				this[type] = true;
			},
			changeDate(type, e) {
				this.docRecordform[type] = this.$u.date(e.timestamp, 'yyyy年mm月dd日 hh时MM分');
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (!this.docRecordform.partyUuids) {
							this.$u.toast('请选择当事人!');
							return;
						}
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			// 保存、提交按钮
			submitBtn(type) {
				if (type == 'preview') {
					if (!this.doc.isRecorded) {
						this.$u.toast('请先保存数据');
						return;
					}
					officeService.buildLocalPunish("/survey/doc-check-record", this.doc.docInsUuid).then(pdfId => {
						if (pdfId.success) {
							this.downloadFile(pdfId.bean, "预览", false);
						} else {
							this.$u.toast(pdfId.msg);
						}
					});
				} else {
					let flag = this.validForm(type);
					if (flag) {
						if (this.employeeLst.length == 0) {
							this.$u.toast('请选择检查人!');
							return;
						}
						this.handleOperBtn(type);
					}
				}
			},
			handleOperBtn(flag) {
				let [docIns, self, ] = [this.docRecordform, this, ];
				let {
					id,
					docUuid,
					titemUuid,
					gfaCode,
					bizUuid,
					caseType,
					caseCode,
				} = this.caseParam;
				docIns.caseUuid = bizUuid;
				docIns.localeDesc = docIns.localeDesc || "";
				flag == 'save' && this.$u.loading('数据保存中...');
				console.log(this.docRecordform);
				console.log(docIns);
				officeService.saveDocCheckRecord(docIns, docUuid, titemUuid, id, gfaCode).then(res => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						docIns.checkRecordUuid = res.bean.checkRecordUuid;
						this.docRecordform = docIns;
						this.saveData = res.data[0];
						self.doc['isRecorded'] = res.data[0].isRecorded;
						self.doc['docInsUuid'] = res.data[0].docInsUuid;
						if (flag == 'submit') {
							console.log(self.signImgList.length)
							this.$u.loading('数据提交中...');
							officeService.submitDocCheckRecord(res.bean, docUuid, titemUuid).then(sRes => {
								this.$u.hideLoading();
								this.saveBehaviorLog(1, this.caseParam, this.doc);
								if (!sRes.success) {
									this.$u.toast(sRes.msg);
									return;
								}
								self.backPrev({
									paramKey: "offiList",
									param: {
										caseUuid: bizUuid,
										caseCode: caseCode,
										caseType: caseType,
									},
								});
							}).catch(er => {
								console.log(er);
								this.$u.hideLoading();
								this.$u.toast(er);
							});
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.hideLoading();
						this.$u.toast(res.msg);
					}
				});
			},
			// 选择模板
			selectModule() {
				let params = {
					bizUuid: this.caseParam.caseUuid,
				};
				if (this.docFields && this.docFields.length > 0) {
					let ob;
					this.docFields.forEach(itm => {
						if ('localeDesc' == itm.fieldName) {
							ob = itm;
						}
					});
					if (ob != undefined) {
						params.docUuid = ob.docUuid;
						params.fieldUuid = ob.fieldUuid;
						params.showType = '1';
					}
				}
				this.setRouteParam(params);
				this.$u.route('pages/case/components/selectLocalDescModule');
			},
			updateBackState(param) {
				if (param.localDesc) {
					this.docRecordform.localeDesc = param.localDesc;
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0
	}
</style>
